package wxpay

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/json"
	"errors"
)

type MidH5 struct {
	WxPayMid
}

func NewMidH5(mchid, appid, mch_api_key string, pem_cert *x509.Certificate, pem_key *rsa.PrivateKey) *MidH5 {
	ent := &MidH5{}
	ent.Appid = appid
	ent.Mchid = mchid
	ent.MchAPIKey = mch_api_key
	ent.MchPrivateKey = pem_key
	ent.MchCertificate = pem_cert
	return ent
}

//支付统一下单
func (ent *MidH5) CreateOrder(data WxH5OrderData) (string, error) {
	var preq WxH5OrderCreateReq
	preq.Sp_appid = ent.Appid
	preq.Sp_mchid = ent.Mchid
	preq.WxH5OrderData = data
	preq.Appid = ""
	preq.Mchid = ""
	if preq.Scene_info.H5_info.SceneType == "" {
		preq.Scene_info.H5_info.SceneType = "Wap"
	}
	data_body, _ := json.Marshal(preq)

	var pret WxH5OrderCreateRet
	const url = "https://api.mch.weixin.qq.com/v3/pay/partner/transactions/h5"
	result, err := WxPayPostV3(&ent.MchParam, url, data_body)
	if err != nil {
		return "", err
	}

	err = json.Unmarshal([]byte(result), &pret)
	if err != nil {
		return "", err
	}
	if pret.H5_url == "" {
		return "", errors.New(pret.Return_msg)
	}

	return pret.H5_url, nil
}
